package com.raidan.dclog;

import java.io.File;
import java.io.IOException;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

import com.raidan.dclog.core.FileUtils;
import com.raidan.dclog.core.Utils;

/**
 * Task for build bat file ^_^
 * 
 * @author raidan
 * 
 */
public class BatTask extends Task {

	public void execute() {
		String librariesDir = getProject().getProperty("librariesDir");
		if (librariesDir == null) {
			throw new BuildException("Property 'libraries' not set.");
		}

		String basicJar = getProject().getProperty("basicJar");
		if (basicJar == null) {
			throw new BuildException("Property 'basicJar' not set.");
		}

		try {

			// Loading BAT template and write version info and
			// libraries, that we using

			String template = FileUtils.loadFromFile(
					getProject().getBaseDir() + "/src/com/raidan/dclog/BatTask.template").toString();
			String version = Utils.replaceAll(Utils.getVersion(), "\n", " ");

			StringBuilder classPath = new StringBuilder(basicJar);
			String libs[] = new File(getProject().getBaseDir() + "/" + librariesDir).list();
			if (libs != null) {
				for (String lib : libs) { // #1
					if (lib.endsWith(".jar")) {
						classPath.append(";").append(librariesDir).append("/").append(lib);
					}
				} // #1 for
			}

			template = Utils.replaceAll(template, "%version%", version);
			template = Utils.replaceAll(template, "%classpath%", classPath.toString());

			getProject().setNewProperty("templateFile", template);

		} catch (IOException io) {
			// Bad
			throw new BuildException(io);
		}

	}
}
